import axios from 'axios'
import qs from 'qs'

// 生成Axios的伪实例
const instance = axios.create({
    baseURL:''
})


// 请求拦截器
instance.interceptors.request.use(config => {
    let token = sessionStorage.getItem("token");
    if (token) {
        config.headers = {
            'Authorization': token
        }
    }
    switch (config.headers['Content-Type']) {
        case 'application/x-www-form-urlencoded':
            config.data = qs.stringify(config.data)
            break;
        default:
            break;
    }
    return config;
})


// 响应拦截器
instance.interceptors.response.use(
    response => {
        if (response.data.data.token) {
            sessionStorage.setItem('token', response.data.data.token);
            sessionStorage.setItem('userInfo', JSON.stringify(response.data.data.userInfo));
        }
        console.log(response)
        return response.data;
    },
    error => {
        console.error(error)
        return new Promise(() => {})
    }

)

export default instance
